package com.example.gulimall.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elasticsearch 初始化
 * 1.导入配置文件信息
 * 2.编写配置,给容器中注入 RestHighLevelClient
 *
 * @author GuLin
 * @date 2021-06-11 10:54
 */
@Configuration
public class GulimallElasticsearchConfig {


    @Value("${search.ipAdr}")
    private String ipAdr;

    /**
     * 这个RequestOptions类保存应该在同一应用程序中的多个请求之间共享的部分请求。
     * 您可以创建一个单例实例，并在所有请求之间共享它：
     */
    public static final RequestOptions COMMON_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//        builder.addHeader("Authorization", "Bearer " + TOKEN);
//        builder.setHttpAsyncResponseConsumerFactory(
//                new HttpAsyncResponseConsumerFactory
//                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esRestHighLevelClient() {
        //官网示例
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(
//                        new HttpHost("localhost", 9200, "http"),
//                        new HttpHost("localhost", 9201, "http")));
        //创建客户端的生成器
        RestClientBuilder builder = null;
        //HttpHost(final String hostname, final int port, final String scheme)
        //设置远程访问主机信息
        HttpHost httpHost = new HttpHost(ipAdr, 9200, "http");
        builder = RestClient.builder(httpHost);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}
